import { redisService } from './service/redis';
import * as WebSocket from "ws";
import { userService } from "./service/user";
import { User } from "./model/user";
const sockets = new Map<WebSocket,any>();
// const tokens : any = {};


export abstract class GameBase {

    /**
     * 通用事件的处理
     * @param ws 
     * @param message 
     */
    async onCommonMessage(ws: WebSocket, message: string) {
        const failed = [false,false,false];
        let data: {
            event: string,
            data: any
        };
        try {
            data = JSON.parse(message);
        }
        catch (e) {
            return failed;
        }
        //没有事件名的，拒绝
        if (!data.event) {
            return failed;
        }

        let user: User | undefined;
        let _data = data.data;
        if (_data.token) {
            user = await userService.getUserInfoByToken(_data.token) as User;
        }
        const noAuthEvents = ['register_pull'];
        if(!sockets.has(ws)){
            //如果不在本服务器且不通过校验的
            if(!noAuthEvents.includes(data.event)){
                return failed;
            }
        }

        switch (data.event) {
            //每个用户进来，首先需要的是注册自身
            case 'register_pull':
                if (user) {
                    this.registerUser(ws,user);
                    // return [_data,user];
                }
                break;

        }
        //不是这个游戏，不响应

        return [data.event,_data,user];
    }

    onClose(ws : WebSocket){
        try{
            const token = sockets.get(ws).token;
            sockets.delete(ws);
            redisService.del("user:server:" + token);
        }
        catch(e){

        }

    }

    onError(ws : WebSocket){
        return this.onClose(ws);
    }

    /**
     * 将一个用户注册到当前的服务器上
     * @param user 
     */
    registerUser(ws : WebSocket,user: User) {

        //将该用户注册到指定服务器
        redisService.set("user:server:" + user.token,(global as any).ServerUUID);
        //绑定到本服务器，不再校验身份
        sockets.set(ws,{
            token : user.token
        });
    }
}